package com.servlet;

import com.bean.Payment;
import com.google.gson.Gson;
import com.service.impl.PaymentServiceImpl;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.sql.SQLException;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.*;

@WebServlet("/PaymentServlet/*")
public class PaymentServlet extends HttpServlet {

    PaymentServiceImpl paymentService = new PaymentServiceImpl();

    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        doGet(request,response);
    }

    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        response.setCharacterEncoding("utf-8");
        response.setContentType("text/html,charset=utf-8");//命令浏览器用什么编码打开文件

        String pathInfo = request.getPathInfo().substring(1);
        if("listAll".equals(pathInfo)){
            listAll(request,response);
        }else if("listByName".equals(pathInfo)){
            listByName(request,response);
        }else if("listAllByPagination".equals(pathInfo)){
            listAllByPagination(request,response);
        }else if("addupd".equals(pathInfo)){
            addupd(request,response);
        }else if("listAllByPaginationSearch".equals(pathInfo)){
            listAllByPaginationSearch(request,response);
        }
    }

    private void listByName(HttpServletRequest request, HttpServletResponse response) {
        String name  = request.getParameter("name");
        try {
            List<Payment> pList = paymentService.selectByName(name);
            Gson gson = new Gson();
            String s =gson.toJson(pList);
            response.getWriter().print(s);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }


    private void listAllByPaginationSearch(HttpServletRequest request, HttpServletResponse response) {
        int offset = Integer.valueOf(request.getParameter("offset"));
        int limit = Integer.valueOf(request.getParameter("limit"));
        String search = request.getParameter("search");

        try {
            List<Payment> paymentList = paymentService.selectAllPaginationSearch(offset,limit,search);

            int total = paymentService.countSearch(search);
            Map<String,Object> map = new HashMap<>();
            map.put("total",total);
            map.put("rows",paymentList);

            Gson gson = new Gson();
            String s =gson.toJson(map);
            response.getWriter().print(s);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    private void addupd(HttpServletRequest request, HttpServletResponse response) {

        String ownerId = request.getParameter("ownerId");
        String paymentType = request.getParameter("paymentType");
        String paymentUnit = request.getParameter("paymentUnit");
        Integer paymentNum = Integer.valueOf(request.getParameter("paymentNum"));
        String paymentPrice = request.getParameter("paymentPrice");
        String paymentTime = request.getParameter("paymentTime").replace("T", " ");

        System.out.println(paymentPrice);
        Map<Integer, Date> payMap = null;
        try {
            payMap = paymentService.selectById(ownerId,paymentType);
            System.out.println(payMap);
            Date oldPaymentTime = new SimpleDateFormat("yyyy").parse("1970");
            int paymentBalance = 0;

            Set<Map.Entry<Integer, Date>> entrySet = payMap.entrySet();

            for (Map.Entry<Integer, Date> entry: entrySet){

                int key = entry.getKey();
                Date value = entry.getValue();
                System.out.println("%%%%%%%"+key+"%%%%%%%%%%%"+value);
                if(value.compareTo(oldPaymentTime)>0){
                    oldPaymentTime = value;
                    paymentBalance = key;
                }
            }

            String[] split = paymentPrice.split("\\.");
            String inPaymentPrice = split[0] + ".00";

            int newPaymentBalance =paymentBalance+Integer.parseInt(paymentPrice);
            String status;
            if(newPaymentBalance<=0){
                status="欠费";
            }else{
                status="已交";
            }
            //用户账户余额单
            Payment p = new Payment(null,ownerId,String.valueOf(Math.round((Math.random()*9+1)*100000)),paymentType,paymentUnit,paymentNum,inPaymentPrice,String.valueOf(newPaymentBalance)+".00",paymentTime,status);

            boolean b = paymentService.insert(p);
            if(b){
                request.setAttribute("msg","缴费成功");
            }else{
                request.setAttribute("msg","缴费失败");
            }
            request.getRequestDispatcher("/property/payment_add.jsp").forward(request,response);
        } catch (SQLException e) {
            e.printStackTrace();
        } catch (ServletException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        } catch (ParseException e) {
            e.printStackTrace();
        }

        //用户缴费单


        try {

        }catch (Exception e) {
            e.printStackTrace();
        }
    }

    private void listAllByPagination(HttpServletRequest request, HttpServletResponse response) {
        int offset = Integer.valueOf(request.getParameter("offset"));
        int limit = Integer.valueOf(request.getParameter("limit"));

        try {
            List<Payment> paymentList = paymentService.selectAllPagination(offset,limit);
            int total = paymentService.count();
            Map<String,Object> map = new HashMap<>();
            map.put("total",total);
            map.put("rows",paymentList);

            Gson gson = new Gson();
            String s =gson.toJson(map);
            response.getWriter().print(s);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }


    private void listAll(HttpServletRequest request, HttpServletResponse response) {

        try {
            List<Payment> paymentList = paymentService.selectAll();

            Gson gson = new Gson();
            String s = gson.toJson(paymentList);
            response.getWriter().print(s);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}
